﻿/*
 * 反射
 * 一切从 Type 开始
 * 动态操作对象
 */

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;

User user = new User() { Id = 1, UserName = "admin", Password = "123456" };

// 获取属性
user.GetType().GetProperties();
// 获取指定数据
user.GetType().GetProperty("Id");

// 获取方法 和 指定方法
user.GetType().GetMethods();
var pwd = user.GetType().GetMethod("HashPassword").Invoke(user, new object?[] { user.Password });
(string name, string password) = user;

// 获取类的特性 和 全部特性
var attrs = user.GetType().GetCustomAttributes();
var attribute = (TableAttribute)user.GetType().GetCustomAttribute(typeof(TableAttribute));
var attr = user.GetType().GetCustomAttribute<TableAttribute>();
Console.WriteLine(attribute.Name);
Console.WriteLine(attr.Name);

// 获取属性的特性 和 全部特性
var filedAttrs = user.GetType().GetProperty(nameof(user.UserName)).GetCustomAttributes();
var filedAttrs2 = user.GetType().GetProperty("UserName").GetCustomAttribute<RequiredAttribute>();
Console.WriteLine(filedAttrs2.ErrorMessage);


Console.ReadKey();

[Table("User")]
class User
{
    public int Id { get; set; }

    [Required]
    public string UserName { get; set; }

    public string Password { get; set; }

    public void Deconstruct(out string userName, out string password)
    {
        userName = this.UserName;
        password = this.Password;
    }

    public override string ToString()
    {
        return $"UserName:{UserName},Password:{Password}";
    }

    public string HashPassword(string password)
    {
        var md5 = MD5.Create();
        var buffer = md5.ComputeHash(Encoding.UTF8.GetBytes(password));
        string hashPassword = string.Empty;
        foreach (var b in buffer)
        {
            hashPassword += b;
        }
        return hashPassword;
    }
}